using System.Timers;

namespace LicenseApp.Client;

/// <summary>
/// 授权监控器 - 定时检查授权状态并提供非阻塞提醒
/// </summary>
public class LicenseMonitor : IDisposable
{
    private readonly System.Timers.Timer _checkTimer;
    private readonly System.Timers.Timer _reminderTimer;
    private bool _disposed = false;

    /// <summary>
    /// 授权状态变化事件
    /// </summary>
    public event EventHandler<LicenseStatusEventArgs>? LicenseStatusChanged;

    /// <summary>
    /// 授权即将到期提醒事件
    /// </summary>
    public event EventHandler<LicenseReminderEventArgs>? LicenseExpiring;

    /// <summary>
    /// 授权已失效事件
    /// </summary>
    public event EventHandler<LicenseExpiredEventArgs>? LicenseExpired;

    private LicenseInfo? _lastLicenseInfo;
    private bool _lastValidStatus = false;

    public LicenseMonitor()
    {
        // 每分钟检查一次授权状态
        _checkTimer = new System.Timers.Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
        _checkTimer.Elapsed += OnCheckTimerElapsed;
        _checkTimer.AutoReset = true;

        // 每3小时提醒一次（当即将到期时）
        _reminderTimer = new System.Timers.Timer(TimeSpan.FromHours(3).TotalMilliseconds);
        _reminderTimer.Elapsed += OnReminderTimerElapsed;
        _reminderTimer.AutoReset = true;

        // 初始检查
        CheckLicenseStatus();
    }

    /// <summary>
    /// 开始监控
    /// </summary>
    public void Start()
    {
        if (_disposed) return;

        _checkTimer.Start();
        _reminderTimer.Start();
    }

    /// <summary>
    /// 停止监控
    /// </summary>
    public void Stop()
    {
        _checkTimer.Stop();
        _reminderTimer.Stop();
    }

    /// <summary>
    /// 立即检查授权状态
    /// </summary>
    public void CheckNow()
    {
        CheckLicenseStatus();
    }

    private void OnCheckTimerElapsed(object? sender, ElapsedEventArgs e)
    {
        CheckLicenseStatus();
    }

    private void OnReminderTimerElapsed(object? sender, ElapsedEventArgs e)
    {
        CheckExpiringReminder();
    }

    private void CheckLicenseStatus()
    {
        try
        {
            var currentLicenseInfo = LicenseValidator.GetLicenseInfo();
            var currentValidStatus = LicenseValidator.IsLicenseValid();

            // 检查状态是否发生变化
            bool statusChanged = false;
            bool licenseInfoChanged = false;

            if (currentValidStatus != _lastValidStatus)
            {
                statusChanged = true;
            }

            if (!AreLicenseInfoEqual(currentLicenseInfo, _lastLicenseInfo))
            {
                licenseInfoChanged = true;
            }

            // 触发状态变化事件
            if (statusChanged || licenseInfoChanged)
            {
                LicenseStatusChanged?.Invoke(this, new LicenseStatusEventArgs
                {
                    IsValid = currentValidStatus,
                    LicenseInfo = currentLicenseInfo,
                    PreviousLicenseInfo = _lastLicenseInfo
                });
            }

            // 检查是否刚刚失效
            if (_lastValidStatus && !currentValidStatus)
            {
                LicenseExpired?.Invoke(this, new LicenseExpiredEventArgs
                {
                    ExpiredLicenseInfo = _lastLicenseInfo
                });
            }

            // 更新状态
            _lastLicenseInfo = currentLicenseInfo;
            _lastValidStatus = currentValidStatus;
        }
        catch
        {
            // 忽略检查过程中的异常
        }
    }

    private void CheckExpiringReminder()
    {
        try
        {
            var licenseInfo = LicenseValidator.GetLicenseInfo();
            if (licenseInfo?.IsExpiringSoon == true)
            {
                LicenseExpiring?.Invoke(this, new LicenseReminderEventArgs
                {
                    LicenseInfo = licenseInfo,
                    RemainingDays = licenseInfo.RemainingDays
                });
            }
        }
        catch
        {
            // 忽略检查过程中的异常
        }
    }

    private static bool AreLicenseInfoEqual(LicenseInfo? info1, LicenseInfo? info2)
    {
        if (info1 == null && info2 == null) return true;
        if (info1 == null || info2 == null) return false;

        return info1.StartDate == info2.StartDate &&
               info1.Days == info2.Days &&
               info1.AgvCount == info2.AgvCount;
    }

    public void Dispose()
    {
        if (_disposed) return;

        Stop();
        _checkTimer?.Dispose();
        _reminderTimer?.Dispose();
        _disposed = true;
    }
}

/// <summary>
/// 授权状态变化事件参数
/// </summary>
public class LicenseStatusEventArgs : EventArgs
{
    public bool IsValid { get; set; }
    public LicenseInfo? LicenseInfo { get; set; }
    public LicenseInfo? PreviousLicenseInfo { get; set; }
}

/// <summary>
/// 授权即将到期提醒事件参数
/// </summary>
public class LicenseReminderEventArgs : EventArgs
{
    public LicenseInfo LicenseInfo { get; set; } = null!;
    public int RemainingDays { get; set; }
}

/// <summary>
/// 授权已失效事件参数
/// </summary>
public class LicenseExpiredEventArgs : EventArgs
{
    public LicenseInfo? ExpiredLicenseInfo { get; set; }
}
